module pwm (clk, write_data, cs, clr_n, read_data, pwm_out); 
input clk; 
input [7:0] write_data; 

input cs;  
input clr_n; 
output [7:0] read_data; 
output pwm_out; 
// 定义period和pulse_width寄存器的内容 
parameter period = 8'hFF;
reg [7:0] pulse_width;
reg [7:0] counter;
reg off; 
reg pwm_out;
reg [7:0] read_data; 
wire  pulse_width_en; //写使能 

always @(posedge clk or negedge clr_n) 
begin 
  if (clr_n==0) 
  begin 
    pulse_width<=8'h00; 
  end 
  else begin 
    if (pulse_width_en) pulse_width<=write_data[7:0];
    else pulse_width<=pulse_width; 
  end 
end 
// period和pulse_width寄存器的读访问 
always @(pulse_width) 
 read_data=pulse_width;
//计数器增加
always @(posedge clk or negedge clr_n) 
begin
  if (clr_n==0) counter<=0; 
  else if (counter>=period-1) counter<=0; 
  else counter<=counter+1; 
end
//端口输出
always @(posedge clk or negedge clr_n) 
begin 
  if (clr_n==0) off<=0;  
  else if (counter>=pulse_width) off <= 1; 
  else off<=0;
end
always @(posedge clk) 
pwm_out<= off;


assign pulse_width_en = cs ; 

endmodule